03. Using Lambda Expressions

Using Lambda Expressions

In this section, you will learn to create and call lambdas.

ND079 JPND C2 L01 A03 Using Lambda Expressions V2

Lambda Expressions

Lambdas are a Java language feature that make it very easy to implement certain kinds of interfaces in Java. When you compare lambda expressions to the traditional way to of implementing a Java interface, lambdas usually result in much cleaner and easier to understand code.

As you saw from the demo, you can use lambdas to greatly shorten you code and make it easier to read.

Code from the Demo

import java.util.List;
import java.util.function.Predicate;

public final class LambdasMain {

  /**
   * Returns the number of strings that match a given condition.
   *
   * @param input the strings that should be tested.
   * @param condition the condition that strings should be tested against.
   * @return the number of strings in the input that match the condition.
   */
  public static long countMatchingStrings(List<String> input, Predicate<String> condition) {
    return input.stream().filter(condition).count();
  }

  public static void main(String[] args) {

    List<String> input = List.of("hello", "\t   ", "world", "", "\t", " ", "goodbye", "  ");

    long numberOfWhitespaceStrings =
            countMatchingStrings(input, s -> s.trim().isEmpty());

    System.out.println(numberOfWhitespaceStrings + " whitespace strings");
  }
}
BinaryOperator<Integer> add =
   (Integer a, Integer b) -> { return a + b; };

System.out.println(add.apply(1, 2));

Which parts of the lambda expression syntax are optional?

SOLUTION:
  • The `return` statement
  • The parameter types
  • The parentheses (when there is just one parameter)
  • The curly braces (`{`, `}`), for single-statement lambdas.

Which of the following are valid lambda expressions?

SOLUTION:
  • `(Double x, int y) -> { return x * y; }`
  • `(x, y) -> x * y`
  • `x -> x * x`
  • `() -> () -> 10`

Key Terms

  • Lambda expression: An expression that can be used to succinctly implement certain interfaces in Java.